<?php

namespace App\Http\Middleware;

use App\Models\System\AppTrack;
use Closure;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class RecordRequest extends Controller
{
    /**
     * Handle an incoming request.
     * @param  $request
     * @param  $next
     * @param    $response
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $res = $next($request);
        if (!in_array($request->path(), [
            'user-side/user_face_attestation', // 添加不记录日志的 API
            ])) {
            Log::info('=========request===========request==========request==========start:', [
                'api:' => $request->url(),
                'authAdmin:' => $this->authAdmin(),
                'path:' => $request->path(),
                'params:' => $request->all(),
                'res' => (json_decode($res->getContent(), true)['code'] ?? '') !== 200 ? $res : ['SUCCESS'], // 返回成功结果 code == 200 就不记录返回结果了
                'end' => '=========end===========end==========end==========end=========end:'
            ]);
        }

        $user = [];
        if(!empty(($this->authAdmin()))) {
            $user = $this->authAdmin()?->toArray();
        }


        AppTrack::create([
            'api' => $request->url(),
            'path' => $request->path() .','. $request->route()->getName(),
            'user_id' => $user['id'] ?? 0,
            'device_id' => $_SERVER['HTTP_DEVICEID'] ?? '',
            'user_info' => $user,
            'lng' => $_SERVER['HTTP_LNG'] ?? 0,
            'lat' => $_SERVER['HTTP_LAT'] ?? 0,
            'params' => $request->all(),
            'plat' => 1,
            'version' => intval($_SERVER['HTTP_VERSION'] ?? 0) // 大版本号
        ]);

        return $res;
    }

    public function terminate($request, $response){
        self::$authAdmin = null;
    }
}
